var emailCodeBtnCanClick = true;

$(function($){
	sendEmailCodeBtn = $(".desc button");
	inputEmail = $("input[name='email']");
	inputCode = $("input[name='emailcode']");
	loginBtn = $(".login-btn");

	inputEmail.on('input propertychange', function() {
		if(emailCodeBtnCanClick && isItelEmail($(this).val())){  //is a itel Email
			sendEmailCodeBtn.attr("disabled",false);
		}else{
			sendEmailCodeBtn.attr("disabled",true);
		}
	});


	sendEmailCodeBtn.on("click",function(event){
		event.preventDefault();
		emailCodeBtnCanClick = false;
		requestEmailCode();
		handleInputEmailBtn();
	});

	loginBtn.on("click",function(event){
		event.preventDefault();
		handleLoginBtn();
	});
});

function isEmail(text){
	var regx = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
	return regx.test(text);
}


function isItelEmail(text){
	var regx = /^\w[-\w.+]*@itel-mobile.com$/;
	return regx.test(text);
}

/**
 * 请求一个email验证码
 * @param  email 
 * @return 
 */
function requestEmailCode(){
	// console.log(email);
	var url = baseUrl + "requestEmailCode";
	var email = inputEmail.val();
	$.get(url, {email: email},function(result){
		if($.isEmptyObject(result) || result.status != "success"){
			sendEmailCodeBtn.text("失败请刷新");
		}else{
			countdown(30,function(nowCount){
				if(nowCount < 1){
					if(isItelEmail(inputEmail.val())){
						sendEmailCodeBtn.attr("disabled",false);
					}
					sendEmailCodeBtn.text("重新发送");
					emailCodeBtnCanClick = true;
				}else{
					sendEmailCodeBtn.text("已发送(" + nowCount + "s)");
				}

			});
		}
	});
}


/**
* 点击了请求email验证码按钮
*/
function handleInputEmailBtn(){
	sendEmailCodeBtn.attr("disabled",true);
	sendEmailCodeBtn.text("已发送(30s)");
}


/**
*	倒计时函数
*/
function countdown(totalcount,fun){
	var timmer = setInterval(function(){
		totalcount--;
		fun(totalcount);

		if(totalcount < 1){
			console.log("计时结束");
			clearInterval(timmer);
		}
	},1000);
}

/**
* 登录
*/
function handleLoginBtn(){
	var url = baseUrl + "login";
	var email = inputEmail.val();
	var code = inputCode.val();

	$.get(url, {email: email,code:code},function(result){
		if($.isEmptyObject(result) || result.status != "success"){
			sendEmailCodeBtn.text("失败请刷新");
		}else{
			
		}
	});
}